<script>
export default {
  name: 'Index'
}
</script>

<script setup>
import {
  ref,
  nextTick,
  watch,
  onMounted,
  onBeforeUnmount,
  onActivated,
  inject,
  defineAsyncComponent
} from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { debounce } from 'lodash'

// import MessageList from '@renderer/views/index/message/message.vue'
// 异步引入组件
const MessageList = defineAsyncComponent(() => import('@renderer/views/index/message/message.vue'))

const pageHeight = ref('100%') // 页面高度
const loading = inject('loading')
const drawer = ref(false) // 用于控制扫码的显示隐藏
const message = ref([]) // 用于接收消息
const qrcode = ref('') // 用于接收二维码地址
const scanned = ref(true) // 用于判断是否扫码成功
const messageList = ref([]) // 用于接收消息列表

const innerRef = ref()
const scrollbarRef = ref()
const isBottom = ref(true) // 是否滚动到底部
let scrollbarHeight = 0 // 滚动条的盒子高度
let scrollHeight = 0 // 滚动条总高度

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  const wrapHeight = innerRef.value.clientHeight
  const scrollbar = scrollbarRef.value
  if (scrollbar && isBottom.value) {
    scrollbar.setScrollTop(wrapHeight)
  }
  await nextTick()
  scrollbarHeight = scrollbar.wrapRef.clientHeight
  scrollHeight = scrollbar.wrapRef.scrollHeight
}
// 监听滚动
function onScroll(event) {
  const { scrollTop } = event
  isBottom.value = scrollTop + scrollbarHeight >= scrollHeight // 判断是否滚动到底部
}

// 监听消息 变化
const setScrollTop = debounce(scrollToBottom, 300)
watch(
  () => messageList.value.length,
  () => setScrollTop()
)

function scrollForceToBottom() {
  isBottom.value = true
  scrollToBottom()
}

const quitApp = () => {
  ElMessageBox.confirm('确认退出吗?', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(app.quit)
    .catch(() => {})
}

// 启动机器人/重启机器人
const startTheRobot = () => {
  loading(true)
  console.log('bot-start')
  app.sendMessage('bot-start')
}

// 监听启动
const botStart = app.onMessage('bot-start', (msg) => {
  console.log('bot-start', msg)
  scanned.value = false
  message.value.push('监听启动 ' + JSON.stringify(msg))
})

// 扫码
const botScan = app.onMessage('bot-scan', (msg) => {
  loading(false)
  console.log('bot-scan', msg)
  if (msg.data.status == 'Scanned') {
    console.log('扫码成功')
    scanned.value = true
  } else {
    console.log('扫码中')
    drawer.value = true
    qrcode.value = msg.data.qrcode
    scanned.value = false
  }
})

// 登陆
const botLogin = app.onMessage('bot-login', (res) => {
  loading(false)
  console.log('bot-login', res)
  message.value.push('登陆 ' + JSON.stringify(res))
  drawer.value = false
  messageList.value.length = 0
  ElMessage({
    type: 'success',
    message: res.msg
  })
})

// 退出
const botLogout = app.onMessage('bot-logout', (res) => {
  console.log('bot-logout', res)
  message.value.push('退出 ' + JSON.stringify(res))
  ElMessage({
    type: 'success',
    message: res.msg
  })
  // setTimeout(() => {
  //   app.restart()
  // }, 1000)
})

// 出错了
const botError = app.onMessage('bot-error', (res) => {
  console.log('bot-error', res)
  message.value.push('出错了 ' + JSON.stringify(res))
  ElMessage({
    type: 'error',
    message: res.msg
  })
})

// 消息
const botMessage = app.onMessage('bot-message', (msg) => {
  console.log('bot-message', msg)
  messageList.value.push(msg)
  message.value.push('消息 ' + JSON.stringify(msg))
  if (message.value.length > 800) {
    message.value.shift() // 移除数组的第一个元素
  }
})

// 好友请求
const botFriendship = app.onMessage('bot-friendship', (msg) => {
  console.log('bot-friendship', msg)
  // message.value.push('好友请求 ' + JSON.stringify(msg))
})

onMounted(() => {
  // 启动机器人
  startTheRobot()
})

onActivated(async () => {
  await nextTick()
  pageHeight.value = document.querySelector('.main-box')?.clientHeight + 'px'
  isBottom.value == true && scrollToBottom()
})

onBeforeUnmount(() => {
  // 移除监听器
  botStart()
  botScan()
  botLogin()
  botLogout()
  botError()
  botMessage()
  botFriendship()
})
</script>

<template>
  <div>
    <div class="container">
      <!-- 消息列表 -->
      <el-scrollbar ref="scrollbarRef" :height="pageHeight" class="h-full" @scroll="onScroll">
        <div ref="innerRef">
          <div
            v-show="!isBottom"
            class="transition-all flex justify-center items-center fixed right-3 bottom-20 w-8 h-8 rounded-full shadow-lg z-10 cursor-pointer opacity-50"
            style="background-color: var(--el-color-info-light-8)"
            @click="scrollForceToBottom"
          >
            <el-icon><Bottom /></el-icon>
          </div>
          <template v-if="messageList.length > 0">
            <MessageList :message-list="messageList"></MessageList>
          </template>
        </div>
      </el-scrollbar>
    </div>

    <!-- 扫码登陆 -->
    <el-drawer
      v-model="drawer"
      title="微信扫码登陆"
      direction="btt"
      lock-scroll
      :show-close="false"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      size="auto"
    >
      <template #default>
        <div class="scan-img">
          <div style="width: 220px; height: 220px" class="relative">
            <el-image class="w-full h-full" :class="{ blur: scanned }" :src="qrcode" fit="fill" />
            <div
              v-if="scanned"
              class="absolute top-0 left-0 w-full h-full bg-black bg-opacity-0 flex flex-col justify-center items-center z-50"
            >
              <el-icon size="32" color="#07C160"><CircleCheck /></el-icon>
              <div class="text-white text-sm mt-2">扫码成功</div>
            </div>
          </div>
        </div>
        <div class="flex flex-row justify-center mt-5 gap-1">
          <el-button class="w-24" type="primary" @click="startTheRobot">刷新二维码</el-button>
          <el-button class="w-24" type="info" @click="quitApp">退出应用</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
.scan-img {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}
:deep(.el-overlay) {
  height: auto;
  backdrop-filter: blur(5px);
}

:deep(.el-drawer) {
  .el-drawer__header {
    margin-bottom: 0;
    text-align: center;
    letter-spacing: 2px;
  }
}
</style>
